<template>
  <div class="app-container">
    <!-- 课程信息表单 -->
    <el-form>
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>
      <!-- 所属分类：级联下拉列表 -->
      <el-form-item label="课程类别">
          <!-- 一级分类 -->
          <el-select
            v-model="courseInfo.subjectParentId"
            placeholder="请选择"
            @change="subjectChanged">
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.title"
              :value="subject.id"/>
          </el-select>
        <label style="margin: 0 0.5rem">-</label>
          <!-- 二级分类 -->
          <el-select v-model="courseInfo.subjectId" placeholder="请选择">
            <el-option
              v-for="subject in subjectLevelTwoList"
              :key="subject.id"
              :label="subject.title"
              :value="subject.id"/>
          </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>
      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <el-input v-model="courseInfo.description" type="textarea" rows="5"/>
      </el-form-item>
      <!-- 课程封面 -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :on-error="handleCoverError"
          :action="BASE_API+'/file/upload'"
          class="cover-uploader">
          <img v-if="courseInfo.cover" :src="courseInfo.cover" style="width:30rem;height:20rem" />
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
      </el-form-item>
    </el-form>

    <div style="text-align:center">
      <el-button :disabled="saveBtnDisabled" type="primary" @click="saveAndNext()">保存并下一步</el-button>
    </div>
  </div>
</template>

<script>
import {getBaseURL} from "@/utils";
import courseApi from "@/api/vid/course";
import subjectApi from "@/api/vid/subject";
import teacherApi from "@/api/vid/teacher";

export default {
  data() {
    return {
      BASE_API: getBaseURL(),
      saveBtnDisabled: false, // 按钮是否禁用
      courseInfo: {// 表单数据
        id: null,
        price: 0,
        lessonNum: 0,
        // 以下解决表单数据不全时insert语句非空校验
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: ''
      },
      teacherList: [], // 讲师列表
      subjectList: [], // 一级分类列表
      subjectLevelTwoList: []// 二级分类列表
    }
  },
  created() {
    if (this.$parent.courseId){
      this.getCourseById(this.$parent.courseId)
    }else{
      // 初始化分类列表
      this.initSubjectList()
    }
    this.initTeacherList()

  },
  methods: {
    getCourseById(id) {
       courseApi.getCourseById(id).then(res => {
         this.courseInfo = res.data
         //初始分类
         subjectApi.getChildList(0).then(re => {
            this.subjectList = re.data
            //加载二级分类
            this.subjectList.forEach(x => {
               if (x.id === this.courseInfo.subjectParentId){
                   subjectApi.getChildList(x.id).then(res => {
                     this.subjectLevelTwoList = res.data
                   })
               }
            })
         })
       })
    },
    // 获取讲师列表
    initTeacherList() {
      teacherApi.pageList(1,10,{}).then(response => {
        this.teacherList = response.data.list
      })
    },

    // 初始化分类列表
    initSubjectList() {
      subjectApi.getChildList(0).then(response => {
        this.subjectList = response.data
      })
    },
    // 选择一级分类，切换二级分类
    subjectChanged(value) {
      subjectApi.getChildList(value).then(response => {
        this.courseInfo.subjectId = ''
        this.subjectLevelTwoList = response.data
      })
    },
    // 上传成功回调
    handleCoverSuccess(res, file) {
      this.courseInfo.cover = res.data
    },

    // 上传校验
    beforeCoverUpload(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 错误处理
    handleCoverError() {
      this.$message.error('上传失败')
    },
    // 保存并下一步
    saveAndNext() {
      this.saveBtnDisabled = true
      if (this.$parent.courseId) {//编辑
        courseApi.updateCourse(this.courseInfo).then(res => {
          this.$message.success('课程编辑成功！')
          this.$parent.active = 1
          this.$parent.courseId = this.courseInfo.id
        })
      } else {//新增
        courseApi.saveCourse(this.courseInfo).then(res => {
          this.$message.success('课程新增成功！')
          this.$parent.active = 1
          this.$parent.courseId = res.data
        })

      }
    },
  }
}
</script>

<style scoped lang="scss">

</style>
